﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Reflection;

namespace GooglePlaces
{
    public class BaseApi
    {
        public string BaseApiURL { get; set; }
        public string ApiKEY = "key=AIzaSyDOkFVm8Me-soO-_4c0n_3nq-_G1xI9qDM";
        public string Output = "json?";
        public string Parameters { get; set; }

        public string APIURL
        {
            get
            {
                return string.Concat(BaseApiURL, Output, Parameters, ApiKEY);
            }
        }

        //Helper method to call the URL and send the response back.
        public string MakeHttpRequestAndGetResponse(string BaseAPIURL)
        {
            var request = (HttpWebRequest)WebRequest.Create(BaseAPIURL);
            request.Method = WebRequestMethods.Http.Get;
            request.Accept = "application/json";
            string text;
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                text = sr.ReadToEnd();
            }

            return text;
        }

        public string ComputeParameters(object o)
        {
            StringBuilder sb = new StringBuilder();
            List<PropertyInfo> list = o.GetType().GetProperties().ToList();
            foreach (PropertyInfo item in list)
            {
                if (item.GetValue(o, null) != null)
                {
                    sb.Append(item.Name.ToLower() + "=" + item.GetValue(o, null).ToString() + "&");
                }
            }
            return sb.ToString();
        }

    }
}
